<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="预警条件" prop="configId">
        <el-select
          v-model="queryParams.configId"
          placeholder="请选择预警条件"
          clearable
          class="!w-240px"
          @change="handleQuery"
        >
          <el-option
            v-for="config in configOptions"
            :key="config.id"
            :label="config.name"
            :value="config.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="证件号码" prop="idNumber">
        <el-input
          v-model="queryParams.idNumber"
          placeholder="请输入身份证号/护照号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="聚集名称" align="center" prop="gatherName"/>
      <el-table-column label="聚集地址" align="center" prop="gatherAddress"/>
      <el-table-column
        label="聚集开始时间"
        align="center"
        prop="startTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="聚集结束时间"
        align="center"
        prop="endTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="预警时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="人数"
        align="center"
        prop="warnPersonCount"
        width="60px"
      />
      <el-table-column label="操作" align="center" min-width="70px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row)"
            v-hasPermi="['member:warning-gather:update']"
          >
            看详情
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        prop="isRead"
        width="100px"
      >
        <template #header>
          <div style="display: flex; align-items: center; justify-content: center;">
            <span>状态</span>
          </div>
        </template>
        <template #default="scope">
          <!-- 核心：用一个 inline-flex 容器包裹所有元素，实现一行排列 + 垂直居中 -->
          <div style="display: inline-flex; align-items: center;">
            <!-- 未读状态：图标+文字 -->
            <template v-if="scope.row.isRead === 0">
              <el-icon color="#F56C6C" size="18">
                <Message/>
              </el-icon>
              <span style="margin-left: 6px; color: #F56C6C;">有未读</span>
            </template>

            <!-- 已读状态：图标+文字 -->
            <template v-else-if="scope.row.isRead === 1">
              <el-icon color="#67C23A" size="18">
                <Check/>
              </el-icon>
              <span style="margin-left: 6px; color: #67C23A;">全已读</span>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import {onMounted, ref, reactive} from 'vue'
import {useRouter} from 'vue-router'
import {dateFormatter} from '@/utils/formatTime'
import Pagination from '@/components/Pagination/index.vue'
import {
  WarnConfigListVo,
  WarnConfigRespVO,
  WarningGatherApi,
  WarningGatherVO
} from '@/api/member/warninggather'
import {useMessage} from "@/hooks/web/useMessage";
import {Check, Message} from "@element-plus/icons-vue";

/** 聚集预警主表（1条记录对应1次聚集事件） 列表 */
defineOptions({name: 'WarningGather'})

const loading = ref(true)
const configLoading = ref(false)
const list = ref<WarningGatherVO[]>([])
const total = ref(0)
const queryFormRef = ref()
const router = useRouter()
const message = useMessage()
// 预警配置下拉框选项
const configOptions = ref<WarnConfigRespVO[]>([])

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  configId: undefined,
  idNumber: undefined,
})

/** 获取预警配置下拉框数据 */
const getConfigOptions = async () => {
  configLoading.value = true
  try {
    // 查询聚集预警类型的配置（warnType=2）
    const params: WarnConfigListVo = {
      warnType: 2
    }
    const data = await WarningGatherApi.getConfigSelect(params)
    configOptions.value = data || []
  } catch (error) {
    message.error('获取预警配置失败')
    console.error('获取预警配置失败:', error)
  } finally {
    configLoading.value = false
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await WarningGatherApi.getWarningGatherPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
/** 打开详情页，传递完整行记录 */
const openDetail = (row: WarningGatherVO) => {
  try {
    // 1. 再次确认id存在（排除id类型问题）
    if (row.id === undefined || row.id === null) {
      throw new Error('记录ID不存在，无法打开详情')
    }

    // 2. 单独序列化row，确保无异常（排查序列化失败）
    let rowDataStr: string;
    try {
      rowDataStr = JSON.stringify(row);
      console.log('序列化后的数据:', rowDataStr); // 确认序列化结果
    } catch (serialError) {
      throw new Error(`数据序列化失败: ${(serialError as Error).message}`);
    }

    // 3. 编码并传递参数
    router.push({
      name: 'WarningGatherPerson',
      params: {
        id: row.id.toString(), // 匹配路由的:id参数
      },
      query: {
        rowData: encodeURIComponent(rowDataStr) // 确保添加到query
      }
    });

    // 4. 验证跳转参数
    console.log('跳转参数:', {
      params: {id: row.id.toString()},
      query: {rowData: encodeURIComponent(rowDataStr)}
    });

  } catch (error) {
    console.error('打开详情失败:', error);
    message.error(`打开详情失败: ${(error as Error).message}`);
  }
};

/** 初始化 **/
onMounted(() => {
  // 先加载配置下拉框，再加载列表数据
  getConfigOptions().then(() => {
    getList()
  })
})
</script>
